package com.paradogs.framework.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: yumi
 * @date: 2023/12/5  21:48
 * @Description: TODO
 */
public class ExcelUtils {

    /**
     * 读取 Excel 并返回数据集合
     * @param excelFile Excel 文件
     * @param targetClass 数据类型
     * @param <T>
     * @return
     */
    public static <T> List<T> read(File excelFile, Class<T> targetClass) {
        ExcelDataTransformListener<T> reader = new ExcelDataTransformListener<>();
        /**
         * 注意要调用 .sheet().doRead() 才会开始读取
         */
        EasyExcel.read(excelFile, targetClass, reader)
                .sheet()
                .doRead();

        return reader.getData();
    }

    public static <T> List<T> readGameData(File excelFile, Class<T> targetClass) {
        GameDataTransformListener<T> reader = new GameDataTransformListener<>();
        /**
         * 注意要调用 .sheet().doRead() 才会开始读取
         */
        EasyExcel.read(excelFile, targetClass, reader)
                .sheet()
                .doRead();

        return reader.getData();
    }

    public static <T> List<T> read(File excelFile, String sheet, Class<T> targetClass) {

        ExcelDataTransformListener<T> reader = new ExcelDataTransformListener<>();

        /**
         * 注意要调用 .sheet().doRead() 才会开始读取
         */
        EasyExcel.read(excelFile, targetClass, reader)
                .sheet(sheet)
                .doRead();

        return reader.getData();
    }

    public static class ExcelDataTransformListener<T> extends AnalysisEventListener<T> {
        @Getter
        private List<T> data = new ArrayList<>();
        /**
         * Excel 获取到每一条数据都会执行一次
         */
        @Override
        public void invoke(T bean, AnalysisContext analysisContext) {
            data.add(bean);
        }
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        }
    }

    public static class GameDataTransformListener<T> extends AnalysisEventListener<T> {
        @Getter
        private List<T> data = new ArrayList<>();
        /**
         * Excel 获取到每一条数据都会执行一次
         */
        @Override
        public void invoke(T bean, AnalysisContext context) {
            int currentRowIndex = context.readRowHolder().getRowIndex();
            if (currentRowIndex <= 1) {
                return;
            }
            data.add(bean);
        }
        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        }

        @Override
        public void onException(Exception exception, AnalysisContext context) throws Exception {
            // 忽略第二行的参数类型 bean 转换报错
        }
    }

}
